home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
NOVA - For the NeXT Workstation
/
NOVA - For the NeXT Workstation.iso
/
Newsletters
/
GEnieUnixNews
/
unxnl-08.92
< prev
next >
Wrap
Text File
|
1992-12-27
|
40KB
|
995 lines
_ _ _ _ _ _
// // //| // // \// N E W S
//_// // |// // /\\ Vol 3, Issue 6 - August 1992
R o u n d T a b l e (tm)
Items of interest to participants of the GEnie Unix RoundTable
The RoundTable SysOps are:
Andy Finkenstadt....ANDY Rick Mobley.........LRARK
Gary Smith..........GARS Brian Riley.........DELPHI
Mike Nolan..........M.NOLAN All Unix SysOps.....UNIXSYSOPS$
We strongly encourage you to contact any or all of us if you have -ANY-
comments or suggestions. This is -YOUR- RoundTable. We are here to make
your participation as pleasant and beneficial as possible.
ED: editor notes - Unix RT as a resource (GARS) Gary Smith
==
The value of the GEnie Unix RoundTable as a resource to you continues to
grow. Since the last newsletter Mark Williams has added Coherent support.
This is an indication of their dedication to their customer base. They
deserve a round of appreciative applause for this attitude.
The internet mail connection to GEnie is now a reality and the Unix RT
will be the resource center for information regarding access to and usage
of this valuable tool. The list of FAQ (Frequently Asked Questions) and
information files in our library explaining aspects of internet is quite
large and growing. The Unix RoundTable has also been providing a internet
help desk in our Real Time Conference area and also in CHAT. See Andy's
Lead SysOp notes below for more on the internet connection and the help
desk.
Thanks to you, our users, the GEnie Unix RoundTable continues to evolve
into the friendly response center we have worked to make it since we came
on line at the end of 1989. Please continue to push us in the directions
you want us to grow with your comments in the Bulletin Board and via the
Feedback Item on our main menu.
Lead Sysop Notes (ANDY) Andrew Finkenstadt
================ Chief Sysop
Conference Announcement
MEET THE GEnie-INTERNET GATEWAY DEVELOPER
Tuesday August 25, 1992 at 10:00pm Eastern Time
Walt Meffert, developer of the Internet Gateway on the GEnie Service, will
be appearing in the Unix Conference Hall on GEnie page 160, keyword UNIX.
Walt will be speaking on issues and topics of interest about the Internet
gateway.
As part of the GEnie Hot Summer Nights promotion, the conference itself
will be covered under the GEnie*Basic Services pricing plan. Seating is
limited, so plan on showing up a few minutes before the hour (but after
9:50pm EDT) to get a front-row chair.
----------
INTERNET Announcement
GEnie is now testing its Internet gateway. YOU can take part in
the public "Beta Test" by stopping at page 207, keyword INTERNET
and signing up for the gateway. (Some charges apply, so be sure
to read the 'About' and 'Rates' menu items before subscribing.)
The Unix RT staff has been excitedly waiting for this public
testing period. In preparation the Unix RT staff has been
working to proudly host a large repository of Internet
information on GEnie in both the bulletin board (category 12) and
in the software libraries. A list of these files can be found by
searching for the keyword "INTERNET" in the software library.
And in addition from now until Thursday, August 13 from 9pm until
midnight eastern daylight time the Unix RT is sponsoring an
INTERNET HELP DESK for those interested in information about
GEnie's Internet Gateway. Just stop by and ask questions and
receive answers LIVE and instantly.
----------
Upload Contest Winners for July (ANDY)
================================
To: S.SUMMERS1 Sean D. Summers
Sub: Congratulations!
Congratulations to Sean Summmers for winning two free days in the
Unix RT.
He uploaded the excellent communication program for Unix called
"pcomm," a ProComm work-alike that supports Xmodem, Ymodem, and
Zmodem, and a scripting capability.
You too can win one or more free days in the Unix RT. Download
file #2346, CONTEST.RULES, for complete instructions and
qualification criteria.
-Andy
----------
usr/local: Items (scripts and news) snarfed from various sources
=========
Comparing Features Available on Various Shells (GARS) Gary Smith
----------------------------------------------
| SHELL TYPE -------->
| FEATURE Bourne CShell Korn TShell
V (sh) (Csh) (ksh) (tcsh)
Aliasing No Yes Yes Yes
History Substitute No Yes Yes Yes
Tilde Substitution No Yes Yes Yes
Array Support No Yes Yes Yes
Relative Speed >Csh --- <sh =Csh
Job Control No Yes Yes Yes
Command Line Edit No Limited vi/Emacs Emacs
Filename Expansion Limited Limited Limited Extensive
Directory Stack No Yes Yes Yes
Built-in Commands Yes >sh >Csh >Csh
Security Poor Poor >Csh >Csh
Keyboard Binding No Limited Limited Yes
Internationalizaton No Yes No No
Diagnostics Very Poor Poor Good Poor
String Manipulation No Yes Yes Yes
MultiBase Arithmetic No No Yes No
I/O Files Open One One Multiple One
and this from Usenet newsgroup comp.unix.shell on shell comparisons:
Article 4856 of comp.unix.shell:
From: deudon@goofi.greco-prog.fr (DEUDON Guillaume.)
Newsgroups: comp.unix.shell
Subject: Re: List of Shells and Descriptions?
Message-ID: <6885@geocub.UUCP>
Date: 2 Jun 92 11:42:45 GMT
References: <1992May29.132111.3144@kocrsv01.delcoelect.com>
Sender: lnews@geocub.UUCP
Organization: Computer Engineering,ENSERB,University Of Bordeaux,FRANCE.
In article <1992May29.132111.3144@kocrsv01.delcoelect.com>
swlodin@kocrsv01.delcoelect.com (Steve Lodin) writes:
>
>Is there a list of shells (sh, csh, ksh, tcsh, bash, zsh, rc, ...)
>along with a history and description of "neat" features? A pointer to
>a FAQ or archive site would be nice.
>Thanks alot!!!
>Steve
From an older posting ...
---------------------------------------------------------------------------
Newsgroups: comp.unix.shell
Subject: An extensive comparison of 'sh' and 'csh' language features
Message-ID: <KLM.91Nov21100557@glyph.cme.nist.gov>
Date: 21 Nov 91 15:05:57 GMT
Sender: news@cme.nist.gov
Distribution: comp
Organization: National Institute of Standards and Technology
Keywords: sh csh scripting interaction language comparison
Below is a presentation which i put together about particularly
consequential functional differences between the 'sh' and the 'csh'
shell command languages. I've seen many assertions, in Unix
introductory books, in news postings, etc., about how sh is better for
scripting, or csh is better for interactions (and sometimes vice-
versa), but i don't think i've ever seen a direct comparison. I'm
posting a start on such a beast in case anyone else might find it
useful, and also because i'm interested in filling in gaps - hearing
from others about important differences in functionality between the
two shell languages that i've missed (or gotten wrong).
The details are taken from the slides i made for an informal
presentation which i gave (at our CLUB - Computer Users Lunch Bunch)
recently at work. The presentation came out of notes that i
accumulated while idly thinking back (a late at night kind of thing,
and in fact, when i actually wound up generating the notes) to my own
experiences switching from csh- to sh-based shells both for scripting
and for my interactive login shell.
There is a preamble before the comparison which presents some of the
rationale i went through for even considering investing the energy to
scope out a whole new shell. Before looking at 'sh' i was very
steeped in 'csh' - i do system and user support, and so answer lots of
shell interaction and script questions, and have implemented a few
very substantial scripts in csh. (Some of you may be familiar with
'8mmbackup', a script that i wrote which a number of people around the
net have been using. I've also done a few other utilities in 'csh',
and now some big ones in 'sh'.) The combination of an interactive
shell with formidable interaction conveniences, like GNU-emacs-like
command-line interaction conveniences and so forth, built in shell
functions, and greater prospects for POSIX compatibility, finally
prompted me to take a serious look, at least, at making the switch to
a 'sh'-based shell.
I can't be more emphatic that scripting in 'sh' is more manageable
than in 'csh', almost without regard to what you're doing, and the
benefits only increase as your job scales up. The point of my
presentation, however, is that 'sh' language strengths are not only of
benefit for scripting - given the addition of user conveniences like
history, tilde notation, command line editing, and so forth, i find
that 'sh' makes a much better interactive command language substrate.
Hopefully this presentation begins to indicate some of the reasons for
this.
Ken Manheimer Nat'l Inst of Standards and Technology
klm@cme.nist.gov (301)975-3539 (Formerly Nat'l Bureau of Standards)
Factory Automation Systems Division Unix Systems Support Manager
I like time. It's one of my favorites.
A Comparison of Primary
UNIX SHELLS
Ken Manheimer (klm@cme.nist.gov)
National Institute of Standards and Technology
WHAT ARE UNIX SHELLS?
- Containers for delivery of explosive charges? Houses for mollusks?
The ones i'm talking about are a sort of container, but in a more
abstract way...
- Unix shells are command interfaces for using computer software.
- In the most rudimentary sense, each command shell, in general,
provides an interactive base from which to successively `launch'
applications.
- Any but the most minimal shell (CPM?) provides means for connecting
things together:
Environment - an operating context with state, which you can use
to adjust/tailor your command interpreter in a systematic way - eg
env vars, command history, command substitution, ...
Glue - mechanisms for connecting together separate application
operations in more than just sequence.
- Differences get complex at this point.
WHAT ARE THE CHOICES ABOUT?
In UNIX, the glue is particularly important. UNIX' adheres to a policy
of promoting pervasive interconnectivity between applications.
- This endows the potential both for powerful benefits in command
composition...
- ... As well as requiring accommodation for the implicit tendency
towards limiting of the power of individual commands.
Sophistication in command shells allowed their effective use beyond
immediate user interaction, as script programs for engaging
applications, in addition to interactive employment.
Divergence of two shells primary shells, csh and sh, stress different
strengths. The choices would be relatively easy if that's all there
was. But it isn't.
IN SIMPLER DAYS...
There was a time, after the beginning but before today, when the
choices were limited to `sh' (particularly the enhanced versions of
bourne shell) and `csh', and their relative strengths are fairly
clear cut (about which, more detail further below).
Sh is a worse interaction language -
lacks job control
lacks command history (indispensable if only for `!!')
lacks tilde abbreviation ("~klm/.cshrc")
Csh is a worse programming language -
lacks scoped functions
lacks fine granularity file IO
often less robust syntax and semantics
(It may even be reasonable to say that, for the times, and combined
with the peculiar compositional strengths of UNIX utilities, the
shells were relatively good at what they were supposed to do.)
A WRINKLE...
Due to `csh' distinct and substantial interaction conveniences, and
despite `sh' programming-language advantages, it has been fairly easy
to choose csh (or some enhanced csh) for your command interaction
mechanism.
But now, suppose that you could have all the interaction benefits of
csh, as well as prevalent refinements, etc, but built on top of either
csh or sh.
** Would the programming benefits of `sh' be of great enough benefit
for the sake of interactive use to warrant the effort of learning a
different command language for use as your login shell?
In fact, two of the most prevalent contemporary alternative shells,
csh-oriented `tcsh' and sh-oriented `bash', are similar enough in pure
interaction refinements that you would have to consider just this
question to decide between them. I think it's worth considering.
THE COMPARISON
Shell (bourne, csh) comparison
INTERACTION CONVENIENCES
- history
- sh: no
- csh: yes
- tilde notation
- sh: no
- csh: yes
- job control
- sh: no
- csh: yes
- invocation shorthand and overload
- See routines, below.
- sh: sh functions - kinda powerful
- csh: aliases - way feeble (but cute)
- excluding merits of sh functions (below),
csh slaughters sh for interaction conveniences.
COMPOSITION OF ROUTINES
- sh: scoped functions
- somewhat scalable - can recurse
- no direct, persistent nested state
- ie, routine 'packages' (modules)
only by virtue of sub-shells.
- csh: alias and labeled goto
- goto - unstructured - no scoping
- alias - textual substitution
- single cmd or *brief* sequence
- also no scoping
- unruly - no syntactic integrity
- bad partitioning between routine
interior and invocation -
outrageously awkward quoting
- can encode syntactic fragments,
eg 'if' part o'if/then/else/endif
- has some "benefits", eg 'ifHostIn'
-----------------------------------
set hostname=`/bin/hostname`
alias ifHostIn echo "\!* | grep -s $hostname;" 'if ($status == 0) then'
alias ifHostNotIn echo "\!* |grep -s $hostname;" 'if ($status==1) then'
# Obtain accurate date from internet date
# server if you're durer, or from durer
# if you're not durer.
ifHostNotIn durer
rdate durer > /dev/null
echo -n " rdate"
else
# india.colorado.edu is a reliable authority:
set rdateMaster=india.colorado.edu
rdate $rdateMaster
echo -n " rdate($rdateMaster)"
endif ## ifHostNotIn durer ##
# BUT YOU CANNOT:
# ifHostIn durer goon lurch squire mogul
# <do some stuff you want to do on them all>
# ifHostNotIn durer
# <do some stuff you want to do on all but durer>
# endif
# endif
# Csh gets badly confused, misses an endif and considers
# *everything* below as being within the condition.
--------------------------------------------
- comparison
- csh routines don't scale up
- no scoping
- limited to brief compositions
- sh routines do, moderately
I/O
- input reads - sh more powerful
- any input line by line: sh only
- This is significant.
- Eg can read and process pipeline
output line-by-line in sh, not
so in csh. (Unless save the output
in a file and do a separate pass
through the entire file for each line!)
- token parsing reads: sh only
- token syntax manipulation: sh only
- by adjusting IFS var value
- see string data type stuff, above
- redirection - sh more powerful
- stderr to stdout: both
- sh: cmd 2>&1
- csh: cmd |& cat
- csh: cmd >& /dev/tty
- stdout to stderr: sh only
- cmd 1>&2
- persistent redirection: sh only
- 4>&1 #register for resurrection
1>& wherever #redirect stdout
cmd #output to 'wherever'
... #Output still to wherever
1>&4 #resume registered stdout
DATA TYPE COMPOSITION AND HANDLING
- string-oriented conditionals
- sh: idioms using IFS for parsing.
For example, a func that gets the
final component of a Unix path:
PathTail () {
# Return final path (or token) component of $1
wasIFS="$IFS"; IFS="/$IFS" #Prepend '/' to IFS repertoire.
for bucket in $1; do : ; done # Loop with '/' as white space.
IFS="$wasIFS" # resurrect preexisting IFS.
echo $bucket; }
While this is a trivial case, the
mechanism is general, useful for
many things...
- csh: var tail/head/... for parsing
- Slightly more convenient but more
limited than corresponding sh idioms
- Neither provides string dissection
(ie, no "substring <string> 3 4")
- (tho u could do it, using, eg, case,
and bending over backwards)
- In sum, csh does some stuff more
conveniently but doesn't do near
as much, nor near as coherently.
- arrays
- csh has array-style ref to tokens
- feebly implemented but terse
- sh uses iteration idioms
- comprehensive but not terse
HASHING
- sh: on demand, settable, clearable
- csh: unitary pre hashing, redoable
- Probably not determined which is
preferable for general case.
FEATURE SUMMARY
- csh has history, tilde, and
(somewhat dubious) syntax-fragment
textual substitution, lacking in sh.
All primarily instrumental in facilitating
command interaction.
- Sh has much more powerful routine
and data composition features,
redirection features, and string
and token handling features. These
are essential programming features.
- (As mentioned,) csh is better for
interaction, and sh is better for programming.
- csh does not scale up as programming language
- some of sh programming advantages are *very*
conducive for interaction.
- Eg, can read and process pipeline
output line-by-line in sh, *not* so
(without heinous finagling) in csh.
- Functions provide much more robust -
powerful and well-behaved - command
substitution mechanism, facilitating
easy (on-the-fly) and deep environment
customization advantages.
- Given inclusion of contemporary interaction
facilities, as in bash and even 'ksh', at
least some people may find distinct advantage
in switching over to a sh-based shell.
That's it.
------------------------------------------------------------------------
Enjoy !
Guillaume.
--
[g.d]
------------------------------------------------------------------------
"These are a few of my favourite things ..."
Tutorials
=========
DOS Does Unix (M.NOLAN) Mike Nolan Part 1 in a series
-------------
Those of us who use more than one type of computer on a daily basis suffer
from a disease called interface-itis. Remembering which wild cards work on
what system, which word processor or editor uses what keys to enter Insert
mode, even remembering what parameters go with which command. And some
of the alternatives get a bit sticky, or is that GUI? <loud groan>
Since this is, after all, the GEnie Unix RoundTable, this is the first in
a series of columns which will explore just how close to a unix-like
environment one can create on a DOS system.
Peruse the Unix RT Library and you will find 200 or more files which deal
with DOS versions of familiar (or not-so-unfamiliar) commands to unix users.
Add to this several commercial products and there is material which will
take several months to cover.
My plan is to first look at the 'complete' packages, and then to
move on to individual commands. (This will mean some double coverage
for certain commands, because there are versions of them in packages
and as individual files.)
This initial installment will deal with the MKS Toolkit, a commercial
package. Being a commercial product, my expectations were high, and
justifiably so. In fact the MKS Toolkit programs will serve as the
benchmark by which I will measure other packages and files.
The MKS Toolkit (Version 3.2c)
=== === ======= ==============
History records that George Washington Carver was the first to make a
silk purse out of a sow's ear. Let it be known that Mortice Kern Systems
(MKS) has nearly achieved the same feat, by providing an environment
under MS-DOS that is very close to Unix. Of course, Carver was a chemist,
MKS's programmers are closer to magicians.
The MKS Toolkit is actually one part of a suite of packages called the
MKS Programming Platform. The other parts are MKS Lex and Yacc, MKS Make,
and MKS RCS. (These will be covered separately in future installments.)
MKS has both DOS and OS/2 versions of the Toolkit, but only the DOS version
is being reviewed here.
There are 126 programs in the MKS Toolkit:
asa awk awkl banner basename bc bdiff c cal calendar cat cd
chmod cksum clear cmp comm compress cp cpio crypt csplit ctags
cut date dc dd deroff dev df diff diff3 diffh dirname du echo
ed egrep env expand expr fg fgrep file find fmt fold getconf
getopt grep gres head help id jobs join kill lc line login
logname look ls m4 mailx man mkdir mksinfo more mv nl nm od pack
passwd paste patch pathchk pax pcat pg pr printf prof ps pwd
rev rm rmdir sed sh size sleep sort spell split strings strip sum
switch sync tail tar tee test time touch tr tsort tty uname
uncompre unexpand uniq unpack unstrip uudecode uuencode vi
wc which who xargs zcat
To be fair, some of these are variants, such as awk and awkl (a version
for large programs), and egrep/fgrep/grep. (There are also separate
versions of awk for systems with and without an 80x87 math co-processor.)
On balance, though, the list is amazingly complete, and the programs are
generally either very faithful replicas of their unix counterparts or
improvements upon them. Most comply with the Posix 2 draft guidelines,
at least to the extent that DOS permits them to. MKS has added some
enhancements of their own to several programs. A GLOB.EXE program takes
care of unix-like wildcard expansions when the Toolkit is run from a DOS
COMMAND.COM shell.
To go through the entire list would take too much space, which for most
commands would say 'this works just like the unix version', so I will
cover only the commands that caught my interest. The 'major' programs
will be covered in more depth in future columns along with their
counterparts in other packages or files. I did find a few errors in
some of the commands, and MKS has acknowledged one of them as not
following the Posix standard.
The 'tar' program tries to make file names comply with DOS's 8.3
restriction, by eliminating all but the last period. (File name
truncation may occur, and it will take the first 8 characters to the
left of the final period and the first 3 characters following it as the
file name.)
Of course, user and group ownership and most of the file permission
attributes cannot be set, since DOS doesn't support them. (As readers of
the Unix RT BBS may recall, one of our users recently used the MKS Toolkit
tar program to unpack an 18MB tar file, containing something like 5000
files in 800 separate directories.)
However, the documentation for tar claims that it will not overwrite an
existing file, which it silently does. Further, the '-w' parameter is
supposed to pause before each operation and wait for a response beginning
with 'y' to proceed with the operation. In fact, a 'y' skips the
operation, and any other response, such as 'n', results in the operation
being performed.
The 'vi' program is excellent, although I did find a minor bug in it,
involving the placement of the cursor after a 'P' or 'p' paste operation.
It is capable of editing very large files, up to 65000 lines each 1K
long. While I didn't actually try one that big, I did successfully edit
a 3MB file. At one point while editing a file I hit several keys near the
BACKSPACE key and the program aborted. There is no recovery mode in DOS,
so I lost a half hour or so of program editing.
The 'more' program is capable of paging backwards through text, and
has options that handle ANSI escape sequences properly. (Unix users
may recognize the paging backwards feature as the 'less' program.)
It is not very tolerant of almost-text files, though.
The 'lc' program lists files in columns, rather like ls, except that it
gives separate lists of directories, files, read-only files, and system
files. 'lc -d' gives a list of only the directories found. I liked this
tool so much I located source for it for my Unix systems. (And uploaded
this source to the Unix RT Library.)
Perhaps the best part of the MKS Toolkit is the misnamed 'sh', actually
the Korn shell. It can be executed from a DOS prompt, loaded as the
primary shell in the CONFIG.SYS file, or even with an 'init' program
to produce a 'login:' prompt, just like on a Unix system. This third
combination permits multiple users to each have separate setups,
including home directories, and entries in the /etc/passwd file can be
used to load the COMMAND.COM shell or Microsoft Windows from the
'login:' prompt.
Neither of my Unix systems have the Korn shell on them, but I was able
to execute several bourne shell scripts, after a few minor changes to
bring file names into DOS compliance. Under COMMAND.COM, the MKS tools
will work with either '/' or '\' in file names, although under the
Korn shell '/' is required since '\' has a special meaning to the
shell interpreter. (This means that when a command line for a DOS
program must have a full file name on it it may take some extra
keystrokes to pass the '\' through the interpreter to the program.)
Under the Korn shell, the 'mailx' command works with separate mail files
for each logon ID, but there is no provision built in for routing mail to
another system.
Under DOS 5.0 and QEMM 386 6.02, the Korn shell leaves 572,000 bytes
of memory free. Using the 'init' program in CONFIG.SYS, this drops
to 568,000. Loading COMMAND.COM from the 'login' prompt leaves 616,000
bytes free. By comparison, using COMMAND.COM as the primary shell leaves
620,000 bytes free.
With a bit of experimentation (and some assistance from MKS Tech Support),
I was able to get our LANtastic LAN software functioning under the MKS Korn
shell and 'init', although I did have to load an 'extra' version of
COMMAND.COM first, using about 2.2K. The LAN setup was on a network
workstation, installing the MKS Toolkit on the network server seemed
to exacerbate an existing and unsolved problem with QEMM intercepts
and illegal instruction traps on our Northgate 486/33 system.
The MKS Toolkit comes on five 3 1/2" diskettes, and takes a healthy 2.2MB
for the program files in /bin, and another 646K in the /etc directory, mostly
for the online man pages file. Adding the dictionary files and 'spell'
takes another 1MB or so.
Installation is fairly straight forward, although it took 20 minutes or
more. The INSTALL program made some changes to the AUTOEXEC.BAT file
(after asking), but placed a SET command at the end of the file, where
it wasn't reached. The CONFIGURE program takes care of setting up several
different configurations, but more advance configurations need to be
tweaked by hand. My first attempt to install manually produced a few
minor problems with some files in the wrong place, a re-install and
CONFIGURE fixed everything up.
Documentation consists of a User's Guide, a Reference Manual, and a DOS
Installation Manual. The User's Guide goes into differences in DOS and
Unix file names at length, and has an excellent tutorial on the Korn
shell. The Reference Manual consists of the same type information
as in the online man pages, although apparently in a bit more depth, and
is organized like a traditional Unix manual, including a permuted index.
The DOS Installation Manual gives several examples for configuring the
MKS Toolkit, especially the Korn shell, including examples beyond the
capabilities of the install and configure procedures, such as dealing
with a LAN.
There is a separate installation disk with the MKS Programming Platform,
which overrides some of the procedures in the MKS Toolkit installation,
but both performed adequately, except as noted earlier.
The MKS Toolkit for DOS has a list price of $249, but the street price
is closer to $229. MKS Awk and MKS VI previously were also available
separately, but according to MKS this option is being discontinued.
Mortice Kern Systems, Inc.
35 King Street North
Waterloo Ontario N2J 2W9 Canada
519-884-2251. (US Orders 800-265-2797.)
------------
Shells - part 3 (LRARK) Rick Mobley
---------------
This is the third part of this series. In the last part we covered more of
the basics and got into some variables. If you missed reading it, I suggest
you go back and review before continuing to press forward. The basics are
important and will help you discover the heart of this and any other
sequence.
Last issue we found several uses of special variables available in the
shell. This issue lets alter some of our own variables to become powerful
shell programmers.
To capture the output of any command as an argument to another command,
place that command line within grave accents (` `). The shell will first
execute the command enclosed within the grave accents. As an example, we can
assign results to variables.
today=`date`
This would assign the current date string to the variable today.
Now, if you want to assign keyboard input to variables you would probably
use the built-in read command.
read first init last
will take input of:
Ricky L. Mobley
and assign first=Ricky; init=L.; last=Mobley
Single (' ') and Double (" ") quote marks have different meanings in the
shell. For instance:
garbage='echo $? $*; ls * | wc'
does nothing but assign that string to the variable garbage. In order to get
those commands to execute or to allow command substitution to take place
would mean using the Double quote as:
command="echo $? $*; ls * |wc"
To hide the special meaning of $, `, and " within double quotes, precede
these characters with a \ (backslash). Outside of double quote marks,
preceding a character with \ is equivalent to placing it within single quote
marks.
Most commands do not know, or care, whether their input or output is
associated with the keyboard, the display, or a file. This makes it very
convenient to create scripts or to store results in files for later perusal.
When a command begins running, it usually expects that three files are
already open: standard input, standard output, and diagnostic or error
output. A number called a file descriptor is associated with each of these
files:
0 - Standard input
1 - Standard output
2 - Diagnostic output (I like to call this 'Standard Error')
A good use of output redirection might be where you expect some error
messages to occur and want to capture them, along with standard output, to a
file for later study. Using a command like:
cmd > file 2>&1
would do just that. Note that the 2>&1 must contain no spaces. This will
associate 1 with file and associate 2 with 1.
The shell provides several flow control commands that are useful in creating
shell procedures:
for name [in word . . .]
do list
done
For each word, sets name to word and executes the commands in list. I use
this when I have received a group of files that begin with !/bin/sh that
need to be executed to extract the programs into individual files. I would
save them in some order like file1.5, file2.5, file3.5, file4.5 and file5.5
and execute them with:
for file in *.5
do
sh $file
done
Now I can sit back and watch each part (1 through 5) get passed to sh. It is
important to edit out any garbage before the !/bin/sh before attempting to
execute it.
case word in
pattern [|pattern] . . .) list;;
[ .
.
.
pattern [|pattern] . . .) list;;
esac
Executes the commands in the list associated with the first pattern that
matches word.
A simple help attempt can be added to your scripts using this method:
case $1 in
-h* )
usage;
exit 1;
;;
-t* )
extra_text=$2;
shift;
;;
esac
Notice 'esac' is 'case' spelled backwards. This would take my first argument
to prog and test for -h or -t and act accordingly by displaying a usage
statement if -h means help.
if list
then list
[elif list] . . .
[else list]
fi
Executes the list following the if keyword. If it returns a zero exit value,
execute the list following the first then. Otherwise, execute the list
following elif (if there is an elif), and if its exit value is zero, execute
the next then. Failing that, execute the list following the else. If no else
list or then list is executed, the if command returns a zero exit value.
if [ X$EDITOR = X]; then
editor=vi
else
editor=$EDITOR
fi
Simple but powerful! Execute a test (if) to see if I have an EDITOR defined.
If not, assign 'vi' as my editor, otherwise assign EDITOR as my editor and
end the test (fi).
while list
do list
done
Executes the list following the while. If the exit value of the last command
in the list is zero, executes the list following do. Continue looping
through the lists until the exit value of the last command in the while list
is nonzero. In other words, continue the loop, test at the bottom, and exit
only when the last command is nonzero.
while :
do
ls -l
sleep 5
done
This means, while forever do ls -l, sleep 5 seconds and continue. You have
to hit the delete key on this one to force an exit. Its useful to watch a
directory while someone spools you a file. When the size stops growing it
has been received.
until list
do list
done
Executes the list following the until. If the exit value of the last command
in the list is nonzero, executes the list following do. Continues looping
through the lists until the exit value of the last command in the until list
is zero. If no commands in the do list are executed, the until command
returns a zero exit value.
Sound familiar, its a !while.
Note:
(list) Executes the commands in list in a subshell.
{list;} Executes the commands in list in the current shell process.
(does not spawn a subshell).
In the next installment I will continue with built in commands and see what
happens when we run the Shell.
Ricky Mobley [lrark]
Little Rock, AR
------------
FAST and NASTY, DOWN and DIRTY: quick fix scripts that do something
================================
Article 5298 of comp.unix.shell:
Path: glsrk!lrark!ddi1!uunet!uunet!van-bc!twg!bill
From: bill@twg.bc.ca (Bill Irwin)
Newsgroups: comp.unix.shell
Subject: Re: Automatic Shell script for watching disk space
Message-ID: <2542@twg.bc.ca>
Date: 14 Jul 92 22:00:51 GMT
References: <HARI.92Jul3231707@robios6.me.wisc.edu>
Reply-To: bill@twg.bc.ca (Bill Irwin)
Organization: The Westrheim Group, Vancouver, B.C., Canada
hari@robios.me.wisc.edu (Kambainathan Hari) writes:
: To begin with I have hardly written any shell scripts & I apologize if
: this seems simple. Here's the problem:
: I am looking for script to check if the /usr partition has exceeded a
: certain % of disk space. If so, to mail me a warning message.
Since none of the replies so far have specifically mentioned SCO
XENIX, I might as well throw out what we use here. I just
noticed that it could probably handle the mail versus display
option more elegantly. It is called "disklow" on our system, so
to mail the output use "disklow username". To display on screen,
just "disklow".
----------------- snip 8< 8< 8< snip ------------
:
Used=95 # Percent of file system used for warning.
Blocks=5000 # Minimum free blocks
Warning=no
[ $# -gt 0 ] && MailTo=$1 # Alternate to mail to.
for Sizes in `df -v | grep -v Filesystem|awk '{print $6}'`
do
if [ $Sizes -gt $Used ]
then Print=yes
fi
done
for Sizes in `df -v | grep -v Filesystem|awk '{print $5}'`
do
if [ $Sizes -lt $Blocks ]
then Print=yes
fi
done
if [ ${Print=no} = yes ]
then
case $MailTo in
[A-z0-9]*)
TempFile=/tmp/dl.$$
echo "File System % Used" >$TempFile
echo "----------- ------ ---------Free Space--------\n"\ >>$TempFile
df -v | grep -v Filesystem | \
awk '{
if( $6 > '$Used' || '$Blocks' > $5 )
printf( "%-10s\t\t%s\t%6d blocks %3d.%1d Mbytes\n", \
$2, $6, $5, $5 * 512 / 1000000, $5 * 512 % 1000000 / 100000 )}'\
>> $TempFile
mail -s "*** WARNING *** Disk Low" $MailTo <$TempFile
rm $TempFile
;;
*)
echo "File System % Used"
echo "----------- ------ ---------Free Space--------\n"
df -v | grep -v Filesystem | \
awk '{
if( $6 > '$Used' || '$Blocks' > $5 )
printf( "%-10s\t\t%s\t%6d blocks %3d.%1d Mbytes\n", \
$2, $6, $5, $5 * 512 / 1000000, $5 * 512 % 1000000 / 100000 )}'
;;
esac
else
echo "No file systems low on space."
fi
----------------- snip 8< 8< 8< snip ------------
--
Bill Irwin - The Westrheim Group - Vancouver, BC, Canada
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
uunet!twg!bill (604) 431-9600 (voice) | Your Computer
bill@twg.bc.ca (604) 430-4329 (fax) | Systems Partner
---------------
REMINDER - This newsletter is being sent to you 'by request'. If you do
not wish to keep receiving it, e-mail a stop notice to GARS. On the other
hand, we would very much appreciate it if you would pass the word that we
do distribute this item near the tenth (10th) of the month of issue to any-
one on GEnie who requests it.
P L E A S E also remember contributions are most welcome. Please e-mail
items and/or suggestions to GARS.
(EOF)
Trademark and Copyright notices:
Unix is a Trademark of UNIX System Laboratories, Inc.; GEnie, LiveWire, and
RoundTable are Trademarks of General Electric Information Services Company;
Xenix and ms-dos are Trademarks of Microsoft Corporation; NeXT and NeXTstep
are Trademarks of NeXT Computer Systems, Inc., Coherent is a Trademark of
Mark Williams Company, Sun is a Trademark of Sun Microsystems, Inc., MKS is
a Trademark of Mortice Kern Systems, Inc.
The contents of this newsletter are copyright(c) 1992 and may be copied whole
or in part only if original credit is included. The GEnie UNIX RoundTable is
not affiliated with AT&T or UNIX System Laboratories, Inc.